<?php
namespace app\erp_meixingtiyu\logic;

use \DateTime;
use \DateInterval;
use \DateTimeZone;

use app\erp_meixingtiyu\model\MemberCard as MemberCardModel;
use app\erp_meixingtiyu\model\MemberCardOrder as MemberCardOrderModel;

class MemberCard
{
    public function getCartByPaginate()
    {
        $model = new MemberCardModel();
        $cards = $model->getList();

        return $cards->toArray();
    }

    public function addCard($params)
    {
        $card = MemberCardModel::add($params);
        return $card->toArray();
    }

    public function deleteCard($cardId)
    {
        return MemberCardModel::destroy($cardId);
    }

    public static function editCard($params)
    {
        $card = MemberCardModel::edit($params);
        return $card->toArray();
    }

    // 获取会员卡的剩余有效天数，根据付款日期 pay_time 和 有效期 effective 计算剩余天数
    public function getRemainingDay($pay_time, $effective)
    {
        $pay_date = new DateTime(null, new DateTimeZone('Asia/shanghai'));
        $pay_date->setTimestamp($pay_time);
        // 购买时间加上有效期，即到期时间
        $effective = (int)$effective + 1;
        $pay_date->add(new DateInterval("P{$effective}D"));

        $now = new DateTime(null, new DateTimeZone('Asia/shanghai'));

        $interval = $now->diff($pay_date);

        return [
            'invert' => $interval->invert,
            'days' => $interval->days,
        ];
    }

    public function getOrderList()
    {
        $model = new MemberCardOrderModel();
        $list = $model->getList();

        foreach ($list as $card) {
            $remaining = $this->getRemainingDay(
                $card->pay_time,
                $card->effective
            );
            $card->remaining_day = $remaining['days'];
            if ($remaining['invert'] == 1) {
                // 已过期
                $card->remaining_day = 0;
            }

            // 如果是有限次数的会员卡，计算会员卡的剩余使用次数
            if ($card->type == 1) {
                $card->remaining_times = $card->limite - $card->used_times;
            }
        }

        return $list->toArray();
    }

    public function getOrderListByDate($dateArr)
    {
        [$startDate, $endDate] = $dateArr;
        $endDateArr = explode('-', $endDate);
        $endDateArr[2] = (int)$endDateArr[2] + 1;
        $endDate = implode('-', $endDateArr);
        $list = (new MemberCardOrderModel)->getListByDate($startDate, $endDate);
        return $list->toArray();
    }
}
